package Runde8;

public abstract class Storage {
	private final int max;
	private int current;
	private int activeworkers;
	
	/**
	 * @postcondition Creates a new storage-facility with given maximum capacity
	 */
	public Storage(int max, int activeworkers) {
		this.max = max;
		this.current = 0;
		this.activeworkers = activeworkers;
	}
	
	/**
	 * @postcondition Returns true or false, whether the storage-facility is empty (current == 0) or not
	 */
	public boolean isEmpty() {
		return (current == 0);
	}

	
	/**
	 * @postcondition Returns true or false, whether the given value could be put into the storage-facility (if stored) or not
	 */
	public synchronized boolean tryPut(int toAdd) {
		if ((current + toAdd) > max) {
			return false;
		} 
		current += toAdd;
		notifyAll();
		return true;
	}
	
	/**
	 * @postcondition Returns true or false, whether the given value could be taken off the storage-facility or not
	 */
	public synchronized boolean tryGet(int toGet) {
		if((current-toGet) < 0) {
			return false;
		}
		current -= toGet;
		notifyAll();
		return true;
	}
	
	/**
	 * @postcondition Used by workers to sign-off work when they're finished. decreases activeworkers by one.
	 */
	public synchronized void signOff(){
		activeworkers--;
	}
	
	/**
	 * @postcondition Returns true of false, whether the storage stills has active workers or not
	 */
	public boolean hasActiveWorkers() {
		return (activeworkers != 0);
	}
	
	/**
	 * @postcondition Returns the current value of stored things in consideration of the maximum value
	 */
	public String report(){
		return this + ": " + current + " / " + max;
	}
	
	/**
	 * @postcondition Returns a readable output of Storage (storage-type's name)
	 */
	public abstract String toString();
}
